package com.dlwx.parttimetalent.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.MapChooseAdapter;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.utils.LogUtils;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MapChooseActivity extends BaseActivity {

    @BindView(R.id.mapview)
    MapView mMapView;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    private static BaiduMap mBaiduMap;
    private static boolean isFirst = true;
    public String lat, longi;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadingDialog.dismiss();
            firstLocation();
        }
    };
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private MapChooseAdapter mAdapter;
    private LatLng chooseLatLin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_map_choose);
        ButterKnife.bind(this);
        initView();
//        loadingDialog.show();
    }

    private void initView() {
        etAddress.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
//                    hideSoftKeyboard();
                    PoiInfo bean = null;
                    if (mAdapter != null) {
                        if (!mAdapter.getDataList().isEmpty()) {
                            bean = mAdapter.getDataList().get(0);
                        }
                    }
                    Intent i = new Intent();
                    i.putExtra("address", etAddress.getText().toString());
                    i.putExtra("city", bean.city);
                    i.putExtra("latlng", chooseLatLin);
                    MapChooseActivity.this.setResult(Constant.CITY_RESULT, i);
                    MapChooseActivity.this.finish();
                    LogUtils.d("IME_ACTION_DONE");
                }
                return true;
            }
        });
        mBaiduMap = mMapView.getMap();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MapChooseAdapter(this);
        mAdapter.setDataList(new ArrayList<PoiInfo>());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        //divider
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.size_1)
//                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.bg)
                .build();
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(divider);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLoadMoreEnabled(false);
        recyclerView.setPullRefreshEnabled(false);
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                PoiInfo bean = mAdapter.getDataList().get(position);
                String name = bean.name;
                Intent i = new Intent();
                i.putExtra("address", name);
                i.putExtra("city", bean.city);
                i.putExtra("latlng", chooseLatLin);
                MapChooseActivity.this.setResult(Constant.CITY_RESULT, i);
                MapChooseActivity.this.finish();
            }
        });

        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        });
        isFirst = true;
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {
            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {
            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                chooseLatLin = mapStatus.target;
                addPoint(chooseLatLin);
                getAddresss(chooseLatLin);
            }
        });

    }

    private void getAddresss(LatLng latLng) {
        //实例化一个地理编码查询对象
        GeoCoder geoCoder = GeoCoder.newInstance();
        //设置反地理编码位置坐标
        ReverseGeoCodeOption op = new ReverseGeoCodeOption();
        op.location(latLng);
        LogUtils.i("latLng=" + latLng.latitude);
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                //获取点击的坐标地址
                String address = arg0.getAddress();
                List<PoiInfo> lists = arg0.getPoiList();

                if (!lists.isEmpty()) {
                    mAdapter.clear();
                    lRecyclerViewAdapter.notifyDataSetChanged();
                    mAdapter.addAll(lists);
                    recyclerView.refreshComplete(mAdapter.getItemCount());
                }
            }
            @Override
            public void onGetGeoCodeResult(GeoCodeResult arg0) {
                LogUtils.i("arg0=" + arg0);
            }
        });
        //发起反地理编码请求(经纬度->地址信息)
        geoCoder.reverseGeoCode(op);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    /**
     * 第一次进入地图快速定位
     */
    private void firstLocation() {
        longi = (String) SPUtils.get(this, Constant.LOCATION_LON, "116.395645");
        lat = (String) SPUtils.get(this, Constant.LOCATION_LAT, "39.929985");
        try {
            double longDou = Double.parseDouble(longi);
            double latDou = Double.parseDouble(lat);
            LatLng latLng = new LatLng(latDou, longDou);
            moveToPoint(latLng, true);
        } catch (Exception e) {
            LogUtils.i(e.toString());
        }
    }

    /***
     * 添加订单marker
     */
    private void addPoint(LatLng point) {
        mBaiduMap.clear();
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.wo);
//构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
//在地图上添加Marker，并显示
        mBaiduMap.addOverlay(option);
//        moveToPoint(point);

    }

    private static void moveToPoint(LatLng latLng, boolean b) {
        if (isFirst) {
            isFirst = b;
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(latLng)
                    .zoom(14)
                    .build();
            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态
            mBaiduMap.animateMapStatus(mMapStatusUpdate);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 当不需要定位图层时关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @OnClick({R.id.tv_confirm, R.id.title_left_one_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_confirm:
                PoiInfo bean = null;
                if (mAdapter != null) {
                    if (!mAdapter.getDataList().isEmpty()) {
                        bean = mAdapter.getDataList().get(0);
                    }
                }
                Intent i = new Intent();
                i.putExtra("address", etAddress.getText().toString());
                i.putExtra("city", bean.city);
                i.putExtra("latlng", chooseLatLin);
                MapChooseActivity.this.setResult(Constant.CITY_RESULT, i);
                MapChooseActivity.this.finish();
                break;
            case R.id.title_left_one_btn:
                this.finish();
                break;
        }
    }
}
